from django.shortcuts import render, redirect, reverse
from user.models import User

# Create your views here.
def index_hangdler(request):
    # 判断session中是否有user
    if 'user' in request.session.keys():
        user = request.session['user']
        context = {'login_user': user}
    else:
        context = {}
    return render(request, 'index.html', context)


def login_handler(request):
    # Get请求，返回登录页面
    if request.method == 'GET':
        return render(request, 'login.html')
    # Post请求，处理表单数据
    else:
        # 得到表单数据
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 获取数据库数据
        users = User.objects.filter(username=username, password=password)

        # 核对数据是否相等
        if users:
            user = users[0]
            # 添加用户信息到session中，重定向到首页
            request.session['user'] = {'id': user.id, 'username': user.username}
            return redirect(reverse('index'))
        else:
            return render(request, 'login.html', context={'message': '账号或密码错误'})


def logout_handler(request):
    # 清除sessionid对应的数据
    #request.session.clear()

    # del 清除sessionid对应的数据
    # del request.session['user']

    # 清除数据库session记录
    request.session.flush()

    # 跳转到首页
    return render(request, 'index.html')